﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using System.Web.UI;

using DotNetNuke.Entities.Modules;

using DesertedRoadStudios.BlogNetNuke.Common;
using DesertedRoadStudios.BlogNetNuke.Components;

namespace DesertedRoadStudios.BlogNetNuke
{
    public partial class Widgets : PortalModuleBase
    {
        private Dictionary<string, string> _settings;
        private BlogNetNukeController bnn = new BlogNetNukeController();

        protected void Page_Load(object sender, EventArgs e)
        {
            _settings = bnn.GetSettings(PortalId, ModuleId);

            if (_settings.Count > 0)
            {
                CheckWidget();
                LoadWidget();
            }
        }

        private void CheckWidget()
        {
            if (!_settings.ContainsKey("ParentBlog"))
                throw new System.Exception("Parent Blog not assigned to this widget.");

            if (!_settings.ContainsKey("Widget"))
                throw new System.Exception("Widget has not been defined.");

            if (!_settings.ContainsKey("WidgetContainerControl"))
                throw new System.Exception("Widget has not been assigned a container control");

        }

        private void LoadWidget()
        {
            BlogTab blog = bnn.GetAllBlogTabInfo(PortalId).Where(b => b.ModuleID == Convert.ToInt32(_settings["ParentBlog"])).First();
            XDocument _doc = Methods.GetParams(this.Context, blog.PortalID, blog.ModuleID, blog.TabID);
            IEnumerable<PostInfo> posts;
            
            if (UserInfo.IsSuperUser)
                posts = bnn.GetAllPosts(blog.PortalID, blog.ModuleID, blog.TabID).Where(p =>
                           p.Status != PostStatus.Deleted);
            else
                posts = bnn.GetAllPosts(blog.PortalID, blog.ModuleID, blog.TabID).Where(p =>
                           p.Status == PostStatus.Published);
            
            object[] parameters = { _doc, _settings, posts };
            UserControl control = Page.LoadControl(_settings["WidgetContainerControl"], parameters);
            Controls.Add(control);
        }
    }
}